<template>
    <div>
        <!-- <el-carousel height="500px" width="1000px" :autoplay="false" trigger="click">
            <el-carousel-item>
                海报
            </el-carousel-item>
            <el-carousel-item>
                视频
            </el-carousel-item>
        </el-carousel> -->
        <div class="poster-div">
            <el-card class="poster">
                <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image">
            </el-card>
        </div>
        <el-col :span="14">
            <div style="margin: 10px;">
                <h1>{{eventInfo.title}}</h1>
                <h3 class="event-status">{{status}}</h3>
                <h3>主办方：{{eventInfo.organizer_name}}</h3>               
                <h3>时间：{{eventInfo.start_time}} 至 {{eventInfo.end_time}}</h3>
                <h3>地点：{{eventInfo.location}}</h3>
                <el-divider></el-divider>
                <h1>详情：</h1>
                <h3>{{eventInfo.details}}</h3>                
                <el-divider></el-divider>
                <h1>评价：</h1>
                <el-row v-for="(r, rIndex) in reviews" :key="rIndex">
                    来自 {{r.username}}<br>
                    评分：{{r.score}}<br>
                    评论：{{r.comment}}<br>
                    {{r.datetime}}<br><br>
                </el-row>
            </div>
        </el-col>
        <el-col :span="10">
            <div style="margin: 30px;">
                <el-card class="box-card">
                    <div class="ticket-info"  v-for="(t, tIndex) in tickets" :key="tIndex">
                        <el-row> 
                            <el-col :span="18">
                                <h3>{{t.name}}</h3>
                            </el-col>
                            <el-col :span="6">
                                <h3>¥ {{t.price}}</h3>
                            </el-col>
                        </el-row>
                    </div>
                    <div style="margin-top: 3px;">
                        <el-button type="primary" round @click="selectTickets()">订票</el-button>
                    </div>
                </el-card>
            </div>
        </el-col>
        
        <el-dialog :visible.sync="dialogVisible_register" width="1200px" center>
            <div style="height: 500px;">
                <el-col :span="16">
                    <div>
                        <h1>{{eventInfo.title}}</h1>
                        <el-divider></el-divider>
                    </div>
                    <el-scrollbar style="height: 450px;">
                        <div style="margin: 20px;">
                            <div v-if="dialogStatus == 'selectTickets'">
                                <el-card v-for="(t, tIndex) in tickets" :key="tIndex" class="ticket-card">
                                    <div slot="header">
                                        <span><b>{{t.name}}</b></span>
                                        <el-select 
                                            v-model="ticketNum[tIndex]" 
                                            placeholder="0" 
                                            :disabled="isTicketSaleEnd[tIndex]"
                                            style="float: right; margin-top: -13px;"
                                        >
                                            <el-option
                                                v-for="(n, index) in t.maxNum+1"
                                                :key="index"
                                                :label="n-1"
                                                :value="n-1">
                                            </el-option>
                                        </el-select>
                                    </div>
                                    <div>
                                        <b>¥ {{t.price}}</b><br>
                                        售票截止时间：{{t.saleEndTime}}<br>
                                        <div v-if="t.returnable">
                                            可退票，截止时间：{{t.returnEndTime}}<br>
                                        </div>
                                        <div v-if="t.transferable">
                                            可转售，截止时间：{{t.transferEndTime}}<br>
                                            可赠予，截止时间：{{t.transferEndTime}}<br>
                                        </div>
                                        有效期截止时间：{{t.validBefore}}<br>
                                        单人最多购买{{t.maxNum}}张票<br>
                                        说明：{{t.description}}<br>
                                    </div>
                                </el-card>
                            </div>
                            <div v-if="dialogStatus == 'setTickets'">
                                <el-card v-for="(bt, btIndex) in buyTickets" :key="btIndex" class="ticket-card">
                                    <div slot="header" style="height: 14px;">
                                        <b>{{tickets[bt.tIndex].name}}</b>
                                    </div>
                                    <div>
                                        <b>¥ {{tickets[bt.tIndex].price}}</b><br>
                                        售票截止时间：{{tickets[bt.tIndex].saleEndTime}}<br>
                                        <div v-if="tickets[bt.tIndex].returnable">
                                            可退票，截止时间：{{tickets[bt.tIndex].returnEndTime}}<br>
                                        </div>
                                        <div v-if="tickets[bt.tIndex].transferable">
                                            可转售，截止时间：{{tickets[bt.tIndex].transferEndTime}}<br>
                                            可赠予，截止时间：{{tickets[bt.tIndex].transferEndTime}}<br><br>
                                            可赠予人名单：
                                            <el-select 
                                                v-if="tickets[bt.tIndex].transferable" 
                                                v-model="bt.granteeList" 
                                                multiple 
                                                placeholder="空即不可赠予" 
                                                @change="$forceUpdate()" 
                                                :multiple-limit="tickets[bt.tIndex].maxNum * 2"
                                                style="margin-top: -13px; width: 300px;"
                                            >
                                                <el-option
                                                    v-for="(u, index) in users"
                                                    :key="index"
                                                    :label="u.username"
                                                    :value="u.address">
                                                </el-option>
                                            </el-select>
                                            <br>
                                        </div>
                                        有效期截止时间：{{tickets[bt.tIndex].validBefore}}<br>
                                        说明：{{tickets[bt.tIndex].description}}<br>
                                    </div>
                                </el-card>
                            </div>
                        </div>
                    </el-scrollbar>
                </el-col>
                <el-col :span="8">
                    <el-row>
                        <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" style="width: 100%;">
                    </el-row>
                    <el-row>
                        <el-scrollbar style="height: 200px;">
                            <div>
                                <h2>订单</h2>
                                    <div v-for="(t, tIndex) in tickets" :key="tIndex">
                                        <el-row v-if="ticketNum[tIndex] != 0">
                                            <el-col :span="18">{{ticketNum[tIndex]}} × {{t.name}}</el-col>
                                            <el-col :span="6">¥ {{ticketNum[tIndex]*t.price}}</el-col>
                                        </el-row>
                                    </div>
                                <el-divider></el-divider>

                                <el-row>
                                    <el-col :span="16">                            
                                        <h2>合计</h2>
                                    </el-col>
                                    <el-col :span="8">
                                        <h2>¥ {{totalFee}}</h2>
                                    </el-col>
                                </el-row>
                            </div>
                        </el-scrollbar>
                    </el-row>
                </el-col>
            </div>
            <span slot="footer">
                <el-button type="primary" v-if="dialogStatus == 'setTickets'" @click="dialogStatus = 'selectTickets'">返回修改</el-button>                
                <el-button type="success" v-if="dialogStatus == 'setTickets'" @click="checkOut()">已完成支付</el-button>
                <el-button type="primary" v-if="dialogStatus == 'selectTickets'" @click="confirmOrder()">确认订单</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>    
import common from "../../utils/common.vue";
import {mapGetters} from 'vuex';

export default {
    data() {
        return {
            status: '',

            eventInfo: {
                id: '',
                title: '',
                location: '',
                start_time: '',
                end_time: '',
                organizer_id: '',
                organizer_name: '',
                details: '',
            },
            tickets: [],
            ticketNum: [], 
            // buyTicketInfo: {
            //     ticketId: '',
            //     granteeList: []
            // },
            buyTickets: [],
            users: [],
            reviews: [],
            isTicketSaleEnd: [],

            dialogStatus: '',
            dialogVisible_register: false,
        }
    },
    created() {
        this.eventInfo.id = this.$route.params.id;

        this.getEventBasicInfo();
        this.getEventDetails();
        this.getTickets();
        this.getAllUsers();
        this.getReviews();
    },
    computed: {
        ...mapGetters([
            'userId',
            'username',
            'address',
        ]),
        totalFee: function() {
            var sum = 0;
            for (let i = 0; i < this.tickets.length; i++) {
                sum += this.ticketNum[i] * this.tickets[i].price;
            }
            return sum;
        },
    },
    methods: {
        getEventBasicInfo() {
            this.api({
                url: "/event/getEventBasicInfo",
                method: "post",
                data: {id: this.eventInfo.id}
            }).then(data => {
                this.eventInfo.title = data.info.title;
                this.eventInfo.location = data.info.location;
                this.eventInfo.start_time = data.info.start_time;
                this.eventInfo.end_time = data.info.end_time;
                this.eventInfo.organizer_name = data.info.organizer_name;
                this.eventInfo.organizer_id = data.info.organizer_id;  
                this.setStatus();          
            })
        },
        getEventDetails() {
            this.api({
                url: "/event/getEventDetails",
                method: "post",
                data: {event_id: this.eventInfo.id}
            }).then(data => {
                this.eventInfo.details = data.info;
            })
        },
        getTickets() {
            this.api({
                url: "/event/getTicketsByEventId",
                method: "post",
                data: {event_id: this.eventInfo.id}
            }).then(data => {
                this.tickets = data.info;
                this._cleanTicketNum();
            })
        },
        getAllUsers() {
            this.api({
                url: "/user/getAllUsers",
                method: "get",
            }).then(data => {
                this.users = data.info;
            })      
        },
        getReviews() {
            this.api({
                url: "/review/getEventReviewHashes",
                method: "post",
                data: {
                    userId: this.userId,
                    eventId: this.eventInfo.id
                }
            }).then(data => {
                console.log("reviews:", data.info)
                this.reviews = data.info;
            })    
        },
        selectTickets() {
            if (this.userId == '') {
                this.$router.push({name: "login"});            
            } 

            this._cleanTicketNum();
            this.buyTickets = [];
            
            for (let i = 0; i < this.tickets.length; i++) {
                let now = Date.now();
                let saleEndTime = new Date(this.tickets[i].saleEndTime).getTime();
                this.isTicketSaleEnd[i] = now >= saleEndTime;
            }

            this.dialogStatus = 'selectTickets';
            this.dialogVisible_register = true;
        },
        confirmOrder() {
            var index = 0;
            for (let i = 0; i < this.tickets.length; i++) {
                for (let j = 0; j < this.ticketNum[i]; j++) {
                    this.buyTickets[index] = {
                        ticketId: this.tickets[i].id,
                        tIndex: i,
                        granteeList: [],
                    }
                    index++;
                }
            }      
            this.dialogStatus = 'setTickets';
        },
        checkOut() {
            let params = {"userId": this.userId, "buyTickets": this.buyTickets}
            this.api({
                url: "/ticketing/mintTickets",
                method: "post",
                data: params
            }).then(data => {
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "您已成功订票",
                        type: 'success'
                    })               
                }
                if (data.code == common.codeFromBackEnd.ERROR_CODE) {
                    this.$message({
                        message: data.msg,
                        type: 'error'
                    })
                }   
                this.dialogVisible_register = false;
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("订票失败")
            })
            
        },
        setStatus() {
            let now = Date.now();
            let endTime = new Date(this.eventInfo.end_time).getTime();
            let startTime = new Date(this.eventInfo.start_time).getTime();
            if (now < startTime) {
                this.status = '未开始';
            } else if (now < endTime) {
                this.status = '正在进行';
            } else {
                this.status = '已结束';
            }
        },

        _cleanTicketNum() {
            for (let i = 0; i < this.tickets.length; i++) {
                this.ticketNum[i] = 0;
            }
        },
    },
}
</script>

<style scoped>
.poster-div {
    width: 1000px;
    height: 500px;
    margin-top: 20px;
}

.poster {
    width: 1000px;
    height: 500px;
}

/* .el-scrollbar__wrap {
    overflow-x: hidden;
} */

.ticket-card {
    width: 600px;
    margin: 20px;
}
    
.event-status {
    font-size: 18px;
    color: #E6A23C;
}
</style>